카테고리별로 나뉘어진 데이터에 대한 통계치를 생성: groupby(), agg(), apply()
netflix_1990 = ( netflix .loc[:, ["title", "rating", "watch_date", "release_year"]] # 특정 열을 선택 .query("release_year >= 1990") # 조건에 맞는 행만 필터링 .assign( # 새로운 열/변수를 생성 decade=lambda x: x["release_year"] //10*10, # 10년 단위 weekday=lambda x: x["watch_date"].dt.day_name().str[:3] # 요일 ) .sort_values("release_year") # 조건에 따라 행을 정렬)netflix_1990
title
rating
watch_date
release_year
decade
weekday
406248
Rocky V
3
2004-02-20
1990
1990
Fri
847433
Rocky V
1
2004-02-13
1990
1990
Fri
268823
Rocky V
2
2005-05-18
1990
1990
Wed
...
...
...
...
...
...
...
476261
King's Ransom
2
2005-08-31
2005
2000
Wed
476074
Coach Carter
2
2005-09-14
2005
2000
Wed
109441
The Amityville Horror
3
2005-11-07
2005
2000
Mon
1149195 rows × 6 columns
표시줄 수 지정
# max number of rows to displaypd.options.display.max_rows =6# resetpd.options.display.max_rows =0
subsetting
변수들(열)과 관측치(행)를 선택
Bracket []
Dot-notation .
iloc, loc
# Bracket [strings]netflix[["title", "rating"]]
title
rating
0
50 First Dates
4
1
Men in Black II
2
2
50 First Dates
4
...
...
...
1246555
Bad Boys II
3
1246556
Something's Gotta Give
4
1246557
The American President
5
1246558 rows × 2 columns
# Bracket [slicing]netflix[:3]
viewer_id
rating
watch_date
release_year
title
record_id
media_type
director
cast
country
date_added
MPAA_rating
duration
genre
description
runtime
num_episodes
0
2191540
4
2004-06-23
2004
50 First Dates
s6019
Movie
Peter Segal
Adam Sandler, Drew Barrymore, Rob Schneider, S...
United States
December 1, 2020
PG-13
99 min
[Comedies, Romantic Movies]
After falling for a pretty art teacher who has...
99
<NA>
1
998702
2
2005-08-26
2002
Men in Black II
s7444
Movie
Barry Sonnenfeld
Tommy Lee Jones, Will Smith, Rip Torn, Lara Fl...
United States
October 1, 2019
PG-13
88 min
[Action & Adventure, Comedies, Sci-Fi & Fantasy]
Will Smith and Tommy Lee Jones reprise their r...
88
<NA>
2
1914163
4
2005-03-21
2004
50 First Dates
s6019
Movie
Peter Segal
Adam Sandler, Drew Barrymore, Rob Schneider, S...
United States
December 1, 2020
PG-13
99 min
[Comedies, Romantic Movies]
After falling for a pretty art teacher who has...
99
<NA>
# dot-notationnetflix.title
0 50 First Dates
1 Men in Black II
2 50 First Dates
...
1246555 Bad Boys II
1246556 Something's Gotta Give
1246557 The American President
Name: title, Length: 1246558, dtype: str
# title에 game이 포함되어 있는 행만 필터링netflix.loc[netflix.title.str.contains("Game"), :] # .str: 문자열 처리# 동일한 작업을 query()를 이용해 필터링netflix.query("title.str.contains('Game')")
viewer_id
rating
watch_date
release_year
title
record_id
media_type
director
cast
country
date_added
MPAA_rating
duration
genre
description
runtime
num_episodes
108
1611338
4
2003-02-27
1997
The Game
s601
Movie
David Fincher
Michael Douglas, Sean Penn, Deborah Kara Unger...
United States
July 1, 2021
R
129 min
[Thrillers]
An aloof investment banker's life spirals into...
129
<NA>
187
2634345
5
2005-06-28
1997
The Game
s601
Movie
David Fincher
Michael Douglas, Sean Penn, Deborah Kara Unger...
United States
July 1, 2021
R
129 min
[Thrillers]
An aloof investment banker's life spirals into...
129
<NA>
245
465580
3
2004-02-09
1997
The Game
s601
Movie
David Fincher
Michael Douglas, Sean Penn, Deborah Kara Unger...
United States
July 1, 2021
R
129 min
[Thrillers]
An aloof investment banker's life spirals into...
129
<NA>
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
1246315
715480
4
2005-08-13
1997
The Game
s601
Movie
David Fincher
Michael Douglas, Sean Penn, Deborah Kara Unger...
United States
July 1, 2021
R
129 min
[Thrillers]
An aloof investment banker's life spirals into...
129
<NA>
1246407
2567821
2
2003-05-18
1997
The Game
s601
Movie
David Fincher
Michael Douglas, Sean Penn, Deborah Kara Unger...
United States
July 1, 2021
R
129 min
[Thrillers]
An aloof investment banker's life spirals into...
129
<NA>
1246415
1154697
4
2004-11-17
1997
The Game
s601
Movie
David Fincher
Michael Douglas, Sean Penn, Deborah Kara Unger...
United States
July 1, 2021
R
129 min
[Thrillers]
An aloof investment banker's life spirals into...
129
<NA>
19341 rows × 17 columns
sort_values()
조건에 맞도록 행을 재정렬
netflix.sort_values("release_year") # year에 대해 오름차순 정렬netflix.sort_values("release_year", ascending=False) # year에 대해 내림차순 정렬netflix.sort_values(["release_year", "rating"], ascending=False) # year 다음 rating에 대해 내림차순 정렬
viewer_id
rating
watch_date
release_year
title
record_id
media_type
director
cast
country
date_added
MPAA_rating
duration
genre
description
runtime
num_episodes
18
86305
5
2005-10-24
2005
The Amityville Horror
s8189
Movie
Andrew Douglas
Ryan Reynolds, Melissa George, Chloë Grace Mor...
United States
January 1, 2020
R
89 min
[Horror Movies]
This hair-raising remake of the 1979 horror hi...
89
<NA>
31
666338
5
2005-08-19
2005
Coach Carter
s6511
Movie
Thomas Carter
Samuel L. Jackson, Rob Brown, Robert Ri'chard,...
United States, Germany
January 1, 2020
PG-13
137 min
[Dramas, Sports Movies]
Controversial basketball coach Ken Carter puts...
137
<NA>
189
642572
5
2005-07-27
2005
Coach Carter
s6511
Movie
Thomas Carter
Samuel L. Jackson, Rob Brown, Robert Ri'chard,...
United States, Germany
January 1, 2020
PG-13
137 min
[Dramas, Sports Movies]
Controversial basketball coach Ken Carter puts...
137
<NA>
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
1230179
2537543
1
2005-12-02
1965
The Cincinnati Kid
s8250
Movie
Norman Jewison
Steve McQueen, Edward G. Robinson, Ann-Margret...
United States
November 1, 2019
TV-14
103 min
[Classic Movies, Dramas]
In Depression-era New Orleans, cocksure stud p...
103
<NA>
1232551
455843
1
2004-01-12
1965
Doctor Zhivago
s6620
Movie
David Lean
Omar Sharif, Julie Christie, Geraldine Chaplin...
United States, Italy, United Kingdom, Liechten...
November 1, 2019
PG-13
200 min
[Classic Movies, Dramas, Romantic Movies]
A young physician and his beautiful mistress g...
200
<NA>
1240585
2185183
1
2005-06-07
1965
Doctor Zhivago
s6620
Movie
David Lean
Omar Sharif, Julie Christie, Geraldine Chaplin...
United States, Italy, United Kingdom, Liechten...
November 1, 2019
PG-13
200 min
[Classic Movies, Dramas, Romantic Movies]
A young physician and his beautiful mistress g...
200
<NA>
1246558 rows × 17 columns
assign()
변수들과 함수들을 이용하여 새로운 변수를 생성
가령, 1990년대, 2000년대 등등과 같이 10년 단위로 새로운 값을 생성하려면,
netflix["release_year"] # pandas Series 객체, 그 값들은 NumPy array
title
50 First Dates 3.752
A Cinderella Story 3.625
About a Boy 3.589
...
Training Day 3.571
Tremors 4: The Legend Begins 3.043
Under Siege 3.313
Name: rating, Length: 94, dtype: Float64
title
50 First Dates min 1
max 5
A Cinderella Story min 1
..
Tremors 4: The Legend Begins max 5
Under Siege min 1
max 5
Name: rating, Length: 188, dtype: int8
def get_basic_stats(db):return {"총 시청 기록수": db.shape[0],"총 시청자 수": db["viewer_id"].nunique(),"고유 작품 수": db["title"].nunique(),"총 시청 시간": db["runtime"].sum() /60,"전체 평균 평점": db["rating"].mean() }get_basic_stats(netflix)
{'총 시청 기록수': 1246558,
'총 시청자 수': 316804,
'고유 작품 수': 94,
'총 시청 시간': 2391943.316666667,
'전체 평균 평점': 3.58698833106843}
NumPy 스칼라값 표현 예전 방식으로 수정
np.set_printoptions(legacy='1.25')
시청자 분석
가장 활발한 시청자 TOP 5
387418: 45회 시청
305344: 43회 시청
1664010: 43회 시청
2439493: 40회 시청
2606799: 38회 시청
# 가장 활발한 시청자 TOP 5netflix.value_counts("viewer_id")[:5].reset_index(name="count")
viewer_id
count
0
387418
45
1
305344
43
2
1664010
43
3
2439493
40
4
2606799
38
시청자별 통계
[6] 시청 횟수: 8회 평균 평점: 3.25/10
[7] 시청 횟수: 14회 평균 평점: 4.07/10
[8] 시청 횟수: 1회 평균 평점: 4.00/10
[10] 시청 횟수: 1회 평균 평점: 4.00/10
[59] 시청 횟수: 1회 평균 평점: 4.00/10
# 시청자별 통계user_stats = netflix.groupby("viewer_id")["rating"].agg(["mean", "std", "count"])user_stats[:5] # 처음 5개 레코드만 표시
mean
std
count
viewer_id
6
3.250
1.035
8
7
4.071
1.141
14
8
4.000
<NA>
1
10
4.000
<NA>
1
59
4.000
<NA>
1
작품별 분석
평균 평점 TOP 10 작품 (최소 3명 이상 평가)
Kabhi Khushi Kabhie Gham
평균 평점: 4.24/10 (97명 평가)
The Pianist
평균 평점: 4.12/10 (30497명 평가)
Coach Carter
평균 평점: 4.07/10 (30022명 평가)
Kuch Kuch Hota Hai
평균 평점: 4.00/10 (271명 평가)
Doctor Zhivago
평균 평점: 3.98/10 (8810명 평가)
Like Water for Chocolate
평균 평점: 3.97/10 (13459명 평가)
American Beauty
평균 평점: 3.96/10 (77407명 평가)
Lock, Stock and Two Smoking Barrels 평균 평점: 3.93/10 (19899명 평가)
Charlotte’s Web
평균 평점: 3.92/10 (13693명 평가)
Jaws
평균 평점: 3.88/10 (40425명 평가)
# 평균 평점 TOP 10 작품 (최소 3명 이상 평가)def get_top_rated_media(n=10, min_ratings=3):return ( netflix .groupby("title")["rating"] .agg(["mean", "count"]) .query("count >= @min_ratings") .nlargest(n, "mean") )get_top_rated_media()
mean
count
title
Kabhi Khushi Kabhie Gham
4.237
97
The Pianist
4.116
30497
Coach Carter
4.071
30022
...
...
...
Lock, Stock and Two Smoking Barrels
3.933
19899
Charlotte's Web
3.917
13693
Jaws
3.880
40425
10 rows × 2 columns
장르 분석
장르별 통계
Comedies: 시청 횟수: 606749회 평균 평점: 3.51/10 시청자 수: 243514명 총 시청 시간: 1083382.5시간
Action & Adventure: 시청 횟수: 466348회 평균 평점: 3.52/10 시청자 수: 217876명 총 시청 시간: 912268.1시간
Dramas: 시청 횟수: 428928회 평균 평점: 3.75/10 시청자 수: 200592명 총 시청 시간: 874892.6시간
…
# 장르별 통계: 시청 횟수, 평균 평점, 시청자 수, 총 시청시간netflix_long = netflix.explode('genre')genre_stats = ( netflix_long.groupby("genre") .agg( count=("rating", "size"), mean_rating=("rating", "mean"), total_viewers=("viewer_id", "nunique"), # nunique(): 고유 값 개수 함수 total_runtime=("runtime", "sum"), ) .assign( total_runtime=lambda x: x["total_runtime"] /60 ) .reset_index())genre_stats
genre
count
mean_rating
total_viewers
total_runtime
0
Action & Adventure
466348
3.518
217876
912268.133
1
Anime Series
126
3.627
126
0.000
2
Children & Family Movies
106728
3.319
69248
163799.883
...
...
...
...
...
...
15
Sports Movies
49586
3.819
45149
104607.100
16
TV Dramas
731
3.765
731
0.000
17
Thrillers
133365
3.551
89527
271388.767
18 rows × 5 columns
# 장르 분포 시각화: 시청 횟수order_by_count = genre_stats.sort_values("count", ascending=False)["genre"].values( so.Plot(genre_stats, y="genre", x="count") .add(so.Bar()) .scale(y=so.Nominal(order=order_by_count)))
시간대 분석
월별 시청 추이
1999-11 1회
1999-12 30회
2000-01 1009회
2000-02 1089회
2000-03 916회
def get_summary_report(db):return {"총 시청 기록 수": db.shape[0],"총 시청자 수": db["viewer_id"].nunique(),"고유 작품 수": db["title"].nunique(),"총 시청 시간": db["runtime"].sum() /60,"전체 평균 평점": db["rating"].mean(),"가장 인기 있는 장르": genre_stats.set_index("genre")["count"].idxmax(),"평균 평점이 가장 높은 TOP 3 작품": get_top_rated_media(3, 3).reset_index().to_dict(orient="records") }get_summary_report(netflix)
{'총 시청 기록 수': 1246558,
'총 시청자 수': 316804,
'고유 작품 수': 94,
'총 시청 시간': 2391943.316666667,
'전체 평균 평점': 3.58698833106843,
'가장 인기 있는 장르': 'Comedies',
'평균 평점이 가장 높은 TOP 3 작품': [{'title': 'Kabhi Khushi Kabhie Gham',
'mean': 4.237113402061856,
'count': 97},
{'title': 'The Pianist', 'mean': 4.116142571400466, 'count': 30497},
{'title': 'Coach Carter', 'mean': 4.070748118046765, 'count': 30022}]}